<template>
    <div class="white-box">
        <div class="table-mb">
            <el-button @click="clickRule">添加等级成长值规则</el-button>
            <el-button type="primary" @click="clickAdd">添加会员等级</el-button>
        </div>
        <el-table
            class="table-mb"
            v-loading="loading"
            :data="arr_data"
            :header-cell-style="{ background: '#F5F7FA' }"
            element-loading-background="rgba(255, 255, 255, 0.6)"
        >
            <el-table-column prop="level_name" label="等级名称"></el-table-column>
            <!-- <el-table-column prop="trade_price" label="交易额"></el-table-column>
            <el-table-column prop="trade_num" label="交易次数"></el-table-column> -->
            <el-table-column prop="exp_point" label="成长值"></el-table-column>
            <el-table-column prop="level" label="权重"></el-table-column>
            <el-table-column label="会员数量">
                <template #default="{ row }">
                    {{ row.user_nums || 0 }}
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="{ row }">
                    <el-button link type="primary" class="theme-btn" @click="clickRights(row)">会员权益</el-button>
                    <el-button link type="primary" class="theme-btn" @click="clickEdit(row)">编辑</el-button>
                    <el-popconfirm title="是否确定删除？" confirm-button-text="确定" cancel-button-text="取消" @confirm="clickDel(row)">
                        <template #reference>
                            <el-button link type="primary" class="theme-btn">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
            background
            v-model:current-page="page"
            v-model:page-size="pageSize"
            :page-sizes="pageSizeNum"
            :total="totalNums"
            layout="total, sizes, prev, pager, next, jumper"
        >
        </el-pagination>

        <!-- 会员权益 -->
        <el-dialog
            v-model="dialogRights"
            draggable
            title="会员权益"
            top="7vh"
            :close-on-click-modal="false"
            width="940px"
            :append-to-body="true"
            :destroy-on-close="true"
            @close="closeRights"
        >
            <el-form ref="ruleOneRef" :model="ruleOneForm" :rules="ruleOneCheck" label-width="140px">
                <!-- <el-form-item label="权益图片" prop="img_paths">
                    <div class="img-list" v-if="ruleOneForm.img_paths">
                        <div class="img-selects">
                            <el-image
                                class="img-selects__pic"
                                :src="proxy.imgUrl + ruleOneForm.img_paths + '!img_400'"
                                :preview-src-list="srcList"
                                fit="cover"
                            />
                            <div class="img-del" @click.stop="delImg">
                                <el-icon size="14px" color="#fff"><CloseBold /></el-icon>
                            </div>
                        </div>
                    </div>
                    <div class="img-box flexs-center" @click.stop="showImg = true" v-else>
                        <el-icon color="#999" size="26px">
                            <UploadFilled />
                        </el-icon>
                    </div>
                    <div class="input-tips">权益等级图片</div>
                </el-form-item> -->
                <el-form-item label="权益说明" prop="rights_text">
                    <div class="editor-box">
                        <Toolbar
                            style="border-bottom: 1px solid #ccc; width: 720px"
                            :editor="editorRef"
                            :defaultConfig="toolbarConfig"
                            mode="default"
                        />
                        <Editor
                            style="height: 360px; overflow-y: hidden; width: 720px"
                            v-model="ruleOneForm.rights_text"
                            :defaultConfig="editorConfig"
                            mode="default"
                            @onCreated="handleCreated"
                        />
                    </div>
                </el-form-item>
                <el-form-item>
                    <div class="flexs" style="margin-top: 20px">
                        <el-button type="primary" :loading="form_loading" @click="submitOneForm(ruleOneRef)"> 确认保存 </el-button>
                        <el-button @click="resetOneForm(ruleOneRef)">取消</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-dialog>
        <!-- 图片库 -->
        <picture-library :show="showImg" :select_multiple="false" @close="showImg = false" @select="selectImg"> </picture-library>

        <!-- 添加/编辑 -->
        <el-dialog
            v-model="dialogUpdate"
            :title="classType == 1 ? '添加会员等级' : '编辑会员等级'"
            :close-on-click-modal="false"
            width="580px"
            :append-to-body="true"
            :destroy-on-close="true"
            @close="closeUpdate"
        >
            <el-form ref="ruleRef" :model="ruleForm" :rules="ruleCheck" label-width="120px">
                <el-form-item label="等级权重" prop="level_weight">
                    <el-input
                        v-model.trim="ruleForm.level_weight"
                        oninput="value=value.replace(/[^\d]/g,'')"
                        clearable
                        placeholder="请输入等级权重"
                    />
                    <div class="input-tips">会员等级权重，值越小越重要（请填写大于0的整数）</div>
                </el-form-item>
                <el-form-item label="等级名称" prop="level_name">
                    <el-input v-model.trim="ruleForm.level_name" clearable placeholder="请输入等级名称" />
                </el-form-item>
                <!-- <el-form-item label="交易额" prop="trade_price">
                    <el-input v-model.trim="ruleForm.trade_price" oninput="value=value.replace(/[^\d.]/g,'')" clearable placeholder="请输入交易额" />
                    <div class="input-tips">满足升级条件之一：交易额</div>
                </el-form-item>
                <el-form-item label="交易次数" prop="trade_num">
                    <el-input v-model.trim="ruleForm.trade_num" oninput="value=value.replace(/[^\d]/g,'')" clearable placeholder="请输入交易次数" />
                    <div class="input-tips">满足升级条件之一：交易次数</div>
                </el-form-item> -->
                <el-form-item label="成长值" prop="exp_value">
                    <el-input v-model.trim="ruleForm.exp_value" oninput="value=value.replace(/[^\d]/g,'')" clearable placeholder="请输入成长值" />
                    <!-- <div class="input-tips">满足升级条件之一：成长值</div> -->
                </el-form-item>
                <el-form-item>
                    <div class="flexs" style="margin-top: 20px">
                        <el-button type="primary" :loading="form_loading" @click="submitForm(ruleRef)">
                            {{ classType == 1 ? "确认添加" : "确认修改" }}
                        </el-button>
                        <el-button @click="resetForm(ruleRef)">重置</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!--添加成长值规则 -->
        <el-dialog
            v-model="dialogRule"
            title="添加成长值规则"
            :close-on-click-modal="false"
            width="640px"
            :append-to-body="true"
            :destroy-on-close="true"
            @close="closeUpdate"
        >
            <el-form ref="ruleLevelRef" :model="ruleLevelForm" :rules="ruleLevelCheck" label-width="100px">
                <el-form-item label="分享">
                    <el-form-item prop="share_people">
                        <el-input
                            v-model.trim="ruleLevelForm.share_people"
                            oninput="value=value.replace(/[^\d]/g,'')"
                            style="width: 140px"
                            clearable
                            placeholder="输入分享人数"
                        />
                    </el-form-item>
                    <el-form-item prop="share_exe" label-width="2px">
                        <span class="rule-item__span">人，赠送</span>
                        <el-input
                            v-model.trim="ruleLevelForm.share_exe"
                            oninput="value=value.replace(/[^\d]/g,'')"
                            style="width: 140px"
                            clearable
                            placeholder="输入成长值"
                        /><span class="rule-item__span">成长值</span>
                    </el-form-item>
                    <div class="input-tips"><code>分享</code>表示分享人数满足条件时，赠送对应成长值</div>
                </el-form-item>
                <el-form-item label="消费">
                    <el-form-item prop="consume_price">
                        <el-input
                            v-model.trim="ruleLevelForm.consume_price"
                            oninput="value=value.replace(/[^\d.]/g,'')"
                            style="width: 140px"
                            clearable
                            placeholder="输入消费金额"
                        />
                    </el-form-item>
                    <el-form-item prop="consume_exe" label-width="2px">
                        <span class="rule-item__span">元，赠送</span>
                        <el-input
                            v-model.trim="ruleLevelForm.consume_exe"
                            oninput="value=value.replace(/[^\d]/g,'')"
                            style="width: 140px"
                            clearable
                            placeholder="输入成长值"
                        /><span class="rule-item__span">成长值</span>
                    </el-form-item>
                    <div class="input-tips"><code>消费</code>表示消费金额满足条件时，赠送对应成长值</div>
                </el-form-item>
                <el-form-item label="访问">
                    <el-form-item>
                        <el-input style="width: 140px" readonly disabled value="1" placeholder="输入访问人数" />
                    </el-form-item>
                    <el-form-item prop="visit_exe" label-width="2px">
                        <span class="rule-item__span">次，赠送</span>
                        <el-input
                            v-model.trim="ruleLevelForm.visit_exe"
                            oninput="value=value.replace(/[^\d]/g,'')"
                            style="width: 140px"
                            clearable
                            placeholder="输入成长值"
                        /><span class="rule-item__span">成长值</span>
                    </el-form-item>
                    <div class="input-tips"><code>访问</code>表示访问店铺1次，赠送对应成长值，访问次数暂不支持修改</div>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" :loading="form_loading" @click="submitLevelForm(ruleLevelRef)">
                        {{ classType == 1 ? "确认添加" : "确认修改" }}
                    </el-button>
                    <el-button @click="resetLevelForm(ruleLevelRef)">重置</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
    <go-back />
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, watch, reactive, shallowRef, onBeforeUnmount } from "vue"
import PictureLibrary from "@components/PictureLibrary.vue"
import OneLoad from "@mixins/one-load"
import GoBack from "@components/GoBack.vue"
import "@wangeditor/editor/dist/css/style.css"
import { Editor, Toolbar } from "@wangeditor/editor-for-vue"

const { proxy } = getCurrentInstance()

onMounted(() => {
    getList()
})

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    ruleOneRef.value = null
    ruleRef.value = null

    if (editorRef.value == null) return
    editorRef.value.destroy()

})

/**
 * minxin列表加载
 */
const { page, pageSizeNum, pageSize, loading, arr_data, totalNums, pubParams, pubRefreshParams, getdata } = OneLoad()
// 切换每页显示条数
watch(pageSize, (val) => {
    page.value = 1
    pubParams(getList)
})
// 跳转第几页
watch(page, (val) => {
    pubParams(getList)
})
function getList() {
    let params = {
        page: page.value,
        limit: pageSize.value,
    }
    getdata("user/grade/index", params)
}

/**
 * 添加会员权益
 * @param {Boolean} dialogUpdate 弹窗状态
 * @param {Array} ruleOneRef 表单规则
 * @param {Object} ruleOneForm  表单字段
 * @param {Object} ruleOneCheck  表单提示
 */
const dialogRights = ref(false)
const ruleOneRef = ref(null)
const ruleOneForm = reactive({
    id: "",
    // img_paths: "",
    rights_text: "",
})
const ruleOneCheck = reactive({
    // img_paths: [{ required: true, message: "请选择权益图片", trigger: "change" }],
    rights_text: [{ required: true, validator: validDesc, trigger: "blur" }],
})
// 权益说明-自定义富文本校验规则
function validDesc(rule, value, callback) {
    let regu = editorRef.value.getText()
    if (regu === "") {
        callback(new Error("请输入权益说明"))
    } else {
        callback()
    }
}
const submitOneForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            let htmls = ruleOneForm.rights_text.replace(/\bhttps?:\/\/(.*?)\/+/gi, "") // 去除图片根域名以及根域名后面的'/'
            form_loading.value = true
            let data = {
                grade_id: ruleOneForm.id,
                // icon: ruleOneForm.img_paths,
                content: htmls,
            }
            proxy.$axios
                .post("user/grade/content", data)
                .then((res) => {
                    form_loading.value = false
                    if (res.data.code == 0) {
                        dialogRights.value = false
                        proxy.$message({ message: "添加成功！", type: "success" })
                        pubParams(getList)
                    } else {
                        proxy.$message({message:res.data.msg,type:"error"})
                    }
                })
                .catch((err) => {
                    form_loading.value = false
                })
        }
    })
}
const resetOneForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
    dialogRights.value = false
    srcList.value = []
    editorRef.value.setHtml("<p></p>") // 重置富文本
}
const clickRights = (row) => {
    ruleOneForm.id = row.grade_id
    getRights(row.grade_id)
    dialogRights.value = true
}
function getRights(id) {
    proxy.$axios
        .get("user/grade/content", {
            params: {
                grade_id: id,
            },
        })
        .then((res) => {
            if (res.data.code == 0) {
                let result = res.data.data
                ruleOneForm.img_paths = result.icon
                srcList.value.push(proxy.imgUrl + result.icon)
                ruleOneForm.rights_text = result.content.replace(/<img [^>]*src=['"]/g, `<img src="${proxy.imgUrl}`) // 往图片追加根域名和'/'
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => {})
}
const closeRights = () => {
    resetOneForm(ruleOneRef.value)
    dialogRights.value = false
}

/**
 * 添加图片
 * @property {Boolean} showImg 显示图片库
 * @property {Function} selectImg 选择图片
 */
const showImg = ref(false)
const srcList = ref([])
const selectImg = (val) => {
    showImg.value = false
    ruleOneForm.img_paths = val[0].photo
    for (let i = 0; i < val.length; i++) {
        srcList.value.push(proxy.imgUrl + val[i].photo)
    }
}
const delImg = () => {
    ruleOneForm.img_paths = ""
    srcList.value = []
}

/**
 * 添加/编辑
 * @param {Boolean} dialogUpdate 添加/编辑弹窗状态
 * @param {Boolean} form_loading 提交按钮状态
 * @param {Number} classType 弹窗类型，1是添加，2是编辑
 * @param {Function} clickAdd 点击添加
 * @param {Function} clickEdit 点击编辑
 * @param {Function} submitForm 确认保存
 */
const dialogUpdate = ref(false)
const form_loading = ref(false)
const classType = ref(1)
const ruleRef = ref(null)
const ruleForm = reactive({
    id: "",
    level_weight: "", // 权重
    level_name: "",
    // trade_price: "",
    // trade_num: "",
    exp_value: "", // 成长值
})
const ruleCheck = reactive({
    level_weight: [{ required: true, message: "请输入等级权重", trigger: "blur" }],
    level_name: [{ required: true, message: "请输入等级名称", trigger: "blur" }],
    // trade_price: [{ required: true, validator: proxy.$util.validNumOrPoint, trigger: "blur" }],
    // trade_num: [{ required: true, message: "请输入交易次数", trigger: "blur" }],
    exp_value: [{ required: true, message: "请输入升级所需的成长值", trigger: "blur" }],
})
const submitForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            if (ruleForm.level_weight <= 0) {
                proxy.$message({ message: "等级权重必须大于0", type: "warning" })
                return
            }
            form_loading.value = true
            let data = {
                level: ruleForm.level_weight,
                level_name: ruleForm.level_name,
                exp_point: ruleForm.exp_value,
                // trade_price: ruleForm.trade_price,
                // trade_num: ruleForm.trade_num,
            }
            if (classType.value == 2) {
                data.grade_id = ruleForm.id
            }
            let url = classType.value == 1 ? "user/grade/add" : "user/grade/update"
            proxy.$axios
                .post(url, data)
                .then((res) => {
                    form_loading.value = false
                    if (res.data.code == 0) {
                        dialogUpdate.value = false
                        proxy.$message({ message: `${classType.value == 1 ? '添加成功！' : '编辑成功！'}`, type: "success" })
                        pubParams(getList)
                    } else {
                        proxy.$message({message:res.data.msg,type:"error"})
                    }
                })
                .catch((err) => {
                    form_loading.value = false
                })
        }
    })
}
const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}
// 点击添加
const clickAdd = () => {
    dialogUpdate.value = true
    classType.value = 1
}
// 点击编辑
const clickEdit = (row) => {
    dialogUpdate.value = true
    setTimeout(() => {
        classType.value = 2
        ruleForm.id = row.grade_id
        ruleForm.level_weight = row.level
        ruleForm.level_name = row.level_name
        // ruleForm.trade_price = row.trade_price
        // ruleForm.trade_num = row.trade_num
        ruleForm.exp_value = row.exp_point
    }, 50)
}
const closeUpdate = () => {
    resetForm(ruleRef.value)
    dialogUpdate.value = false
}

/**
 * 添加成长值规则
 * @param {Boolean} dialogRule 规则弹窗
 * @param {Function} clickRule 点击添加规则
 * @param {Function} submitLevelForm 确认保存
 */
const dialogRule = ref(false)
const ruleLevelRef = ref(null)
const clickRule = () => {
    dialogRule.value = true
    getLevelRule()
}
const ruleLevelForm = reactive({
    share_people: "",
    share_exe: "0",
    consume_price: "",
    consume_exe: "0",
    visit_exe: "0",
})
const ruleLevelCheck = reactive({
    share_people: [{ required: true, message: "", trigger: "blur" }],
    share_exe: [{ required: true, message: "", trigger: "blur" }],
    consume_price: [{ required: true, validator: validNumOrPoint, trigger: "blur" }],
    consume_exe: [{ required: true, message: "", trigger: "blur" }],
    visit_exe: [{ required: true, message: "", trigger: "blur" }],
})
const submitLevelForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            form_loading.value = true
            let data = {
                share_num: ruleLevelForm.share_people,
                share_exp_point: ruleLevelForm.share_exe,
                pay_amount: ruleLevelForm.consume_price,
                pay_exp_point: ruleLevelForm.consume_exe,
                view_num: 1,
                view_exp_point: ruleLevelForm.visit_exe,
            }
            proxy.$axios
                .post("user/grade/expPoint", data)
                .then((res) => {
                    form_loading.value = false
                    if (res.data.code == 0) {
                        dialogRule.value = false
                        proxy.$message({ message: "添加成功！", type: "success" })
                        pubParams(getList)
                    } else {
                        proxy.$message({message:res.data.msg,type:"error"})
                    }
                })
                .catch((err) => {
                    form_loading.value = false
                })
        }
    })
}
const resetLevelForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}
function validNumOrPoint(rule, value, callback) {
    let regu = /^\d+(\.\d{1,2})?$/
    if (value === "") {
        callback(new Error(""))
    } else if (!regu.test(value)) {
        callback(new Error(""))
    } else {
        callback()
    }
}
// 获取成长值规则
function getLevelRule() {
    proxy.$axios
        .get("user/grade/expPoint")
        .then((res) => {
            if (res.data.code == 0) {
                let result = res.data.data
                ruleLevelForm.share_people = result.share_num
                ruleLevelForm.share_exe = result.share_exp_point
                ruleLevelForm.consume_price = result.pay_amount
                ruleLevelForm.consume_exe = result.pay_exp_point
                ruleLevelForm.visit_exe = result.view_exp_point
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => {})
}

// 删除
const clickDel = (row) => {
    proxy.$axios
        .post("user/grade/delete", {
            grade_id: row.grade_id,
        })
        .then((res) => {
            if (res.data.code == 0) {
                pubParams(getList)
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => {})
}

/**
 * 富文本编辑器
 * @param {Object} editorConfig 编辑器配置
 * @param {Object} toolbarConfig 工具栏配置
 * @param {Function} createEditor 创建编辑器
 * @param {Function} createToolbar 创建工具栏
 * @param {Function} handleChange 编辑器内容变化
 */
const editorRef = shallowRef() // 编辑器实例，必须用 shallowRef
const toolbarConfig = {
    // 排除不需要的菜单
    excludeKeys: ["insertLink", "insertImage", "editImage", "viewImageLink", "group-video", "emotion", "fullScreen"],
}
const editorConfig = { placeholder: "请输入内容...", MENU_CONF: {} }
const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}
editorConfig.MENU_CONF["uploadImage"] = {
    // 自定义上传
    async customUpload(file, insertFn) {
        let data = new FormData()
        data.append("from", "article")
        data.append("image", file)
        proxy.$axios
            .post("upload/image", data)
            .then((res) => {
                if (res.data.code == 0) {
                    let url = proxy.imgUrl + res.data.data.path
                    insertFn(url) // 最后插入图片 insertFn(url, alt, href)，alt：描述，href:链接，后面非必填
                } else {
                    proxy.$message({message:res.data.msg,type:"error"})
                }
            })
            .catch((err) => {})
    },
}
</script>
<script>
export default {
    name: "MemberLevel",
}
</script>

<style lang="less" scoped>
.rule-item__span {
    padding: 0px @padding-xs;
}
.editor-box {
    border: 1px solid #ccc;
    border-radius: 2px;
}
</style>
